// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// B [author] rhyme_lph
// s [email]  rhymelph@gmail.com
// U [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/employee_contact_entity.dart';
import 'package:finance_app/src/entities/leave_type_entity.dart';
import 'package:finance_app/src/http_service/http_leave_service.dart';
import 'package:finance_app/src/provider/dashboard_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/hr_and_payroll_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/views/leave_provider.dart';
import 'package:finance_app/src/router_gen/override_route_providers.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:flutter/material.dart';

class LeaveAdjustmentProvider extends BaseProvider {
  List<EmployeeContactEntity> selectEmployeeList;
  List<EmployeeContactLeaveData> leaveData = [];

  @override
  Future get dataFuture => null;

  void onSelectEmployee() async {
    final result = await Routes.navigateTo(
        RouterGenProviders.employeeBatchSelectPage,
        params: {
          'isSelectMode': true,
        });
    if (result != null) {
      selectEmployeeList = result;
      update();
    }
  }

  bool isAll = false;

  void onChangeIsAll(bool isAll) {
    this.isAll = isAll;
  }

  void onSave() {
    if (selectEmployeeList.length == 0) {
      showToast(S.current.please_select_employees);
      return;
    }
    if (leaveData.length == 0) {
      showToast(S.current.please_select_leave_type);
      return;
    }
    List<int> employeeIds = selectEmployeeList.map((e) => e.id).toList();
    List leaveTypes = [];
    for (final item in leaveData) {
      leaveTypes.add({
        'leave_type_id': Config.settingData.leaveType
            .firstWhere((element) => element.key == item.name,
                orElse: () => null)
            .id,
        'days': item.amount,
      });
    }
    obtainContext?.call((context) async {
      final result = await showAdjustLeaveBottomSheet(context);
      if (result == true) {
        bool isSuccess = false;
        await post(HttpLeaveService.batchLeaveAdjust(employeeIds, leaveTypes),
            autoHandler: AutoHandler.Toast,
            loadingTip: S.current.loading, onSuccess: (result) {
          isSuccess = true;
        });
        if (isSuccess == true) {
          await showLeaveAdjustedSuccessBottomSheet(context);
          Providers.get<HrAndPayrollProvider>(
                  RouterGenProviders.hrAndPayrollPage, null)
              ?.getChildProvider<LeaveProvider>()
              ?.refreshController
              ?.requestRefresh();
          if (!Config.hasPermission(PermissionUtils.homeDashboard))
            Config.dashboardProvider
                ?.getChildProvider<HrAndPayrollProvider>()
                ?.getChildProvider<LeaveProvider>()
                ?.refreshController
                ?.requestRefresh();
          Navigator.of(context).pop();
        }
      }
    });
  }

  void onAddLeaveType() {
    obtainContext?.call((context) async {
      final result = await Routes.navigateTo(
          RouterGenProviders.selectAdjustmentLeaveTypePage);
      if (result != null) {
        leaveData.add(EmployeeContactLeaveData()
          ..name = (result['leaveType'] as LeaveTypeEntity).key
          ..amount = int.parse(result['amount']));
        update();
      }
    });
  }

  void onChangeAnnualLeave(EmployeeContactLeaveData e, int value) {
    e.amount = value;
    update();
  }

  void onChangeLeaveType(EmployeeContactLeaveData e) {
    // obtainContext?.call((context) async {
    //   final leaveType = Config.settingData.leaveType
    //       .firstWhere((element) => element.key == e.name, orElse: () => null);
    //   final result = await showAddLeaveTypeBottomSheet(
    //     context,
    //     e.amount?.toString(),
    //     leaveType,
    //   );
    //   if (result != null && result is Map) {
    //     e.name = (result['leaveType'] as LeaveTypeEntity).key;
    //     e.amount = int.parse(result['amount']);
    //     update();
    //   } else if (result != null && result is bool) {
    //     leaveData.remove(e);
    //     update();
    //   }
    // });
  }
}
